package com.ndp.fb.rdb.mongo.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteConcern;
import com.ndp.fb.constant.MongoConstants;
import com.ndp.fb.enums.customaudience.OperateType;
import com.ndp.fb.model.CustomAudienceTemplateRoster;
import com.ndp.fb.mongo.api.CustomAudienceTemplateMongoService;
import com.ndp.fb.util.ListUtil;

/**
 * Created by elvisxiong on 15/11/13.
 */
@Service
public class CustomAudienceTemplateMongoServiceImpl implements CustomAudienceTemplateMongoService {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private DB mongoDBClientPrimary;

    @Override
    public void saveCustomAudienceTemplateRoster(Long custAudienceTemplateId, List<CustomAudienceTemplateRoster> rosters) {
        if (ListUtil.isEmpty(rosters)) {
            logger.info(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER + "入库对象为空，退出入库操作");
            return;
        }
        try {
            DBCollection collection = mongoDBClientPrimary.getCollection(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER);
            List<DBObject> list = new ArrayList<>(rosters.size());
            for (CustomAudienceTemplateRoster roster : rosters) {
                BasicDBObject doc = new BasicDBObject();
                doc.put("customAudienceTemplateId", custAudienceTemplateId);
                doc.put("type", roster.getType());
                doc.put("value", roster.getValue());
//                collection.update(doc,doc,true,false);
                list.add(doc);
            }
            collection.insert(list,WriteConcern.JOURNALED);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER + "集合插入数据完成");
    }

    @Override
    public List<CustomAudienceTemplateRoster> getCustomAudienceTemplateRoster(Long customAudienceTemplateId) {
        List<CustomAudienceTemplateRoster> customAudienceRosterList = new ArrayList<CustomAudienceTemplateRoster>();
        try {
            DBCollection collection = mongoDBClientPrimary.getCollection(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER);
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("customAudienceTemplateId", customAudienceTemplateId);
            DBCursor cursor = collection.find(searchQuery);
            //循环输出结果
            collectCustomRoster(customAudienceTemplateId, customAudienceRosterList, cursor);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER + "查询数据完成");
        return customAudienceRosterList;

    }


    @Override
    public void deleteCustomAudienceTemplateRosters(Long templateIdLong, List<CustomAudienceTemplateRoster> rosters) {
        try {
            DBCollection collection = mongoDBClientPrimary.getCollection(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER);
            List<String> valueList = new ArrayList<>();
            for (int i = 0; i < rosters.size(); i++) {
                CustomAudienceTemplateRoster customAudienceTemplateRoster = rosters.get(i);
                String value = customAudienceTemplateRoster.getValue();
                valueList.add(value);
                if (valueList.size() == 1000 || i + 1 == rosters.size()) {
                    BasicDBObject searchQuery = new BasicDBObject();
                    searchQuery.put("customAudienceTemplateId", templateIdLong);
                    searchQuery.put("value", new BasicDBObject("$in", valueList));
                    collection.remove(searchQuery);
                    valueList.clear();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER + "删除数据完成");
    }

    @Override
    public void deleteALlCustomAudienceTemplateRosters(Long templateIdLong) {
        try {
            DBCollection collection = mongoDBClientPrimary.getCollection(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER);
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("customAudienceTemplateId", templateIdLong);
            collection.remove(searchQuery);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_ROSTER + "删除数据完成");
    }

    @Override
    public void saveCustomAudienceRosterHistory(Long custAudienceId, String version, OperateType operateType, String creator,
                                                List<CustomAudienceTemplateRoster> customAudienceTemplateRosters) {
        if (ListUtil.isEmpty(customAudienceTemplateRosters)) {
            logger.info(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_HISTORY + "入库对象为空，退出入库操作");
            return;
        }
        try {
            DBCollection collection = mongoDBClientPrimary.getCollection(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_HISTORY);
            List<DBObject> transform = Lists.transform(customAudienceTemplateRosters, customAudienceRoster -> {
                BasicDBObject doc = new BasicDBObject();
                doc.put("customAudienceTemplateId", custAudienceId);
                doc.put("version", version);
                doc.put("creator", creator);
                doc.put("operateType", operateType.getValue());
                doc.put("createtime", new Date().getTime());
                doc.put("type", customAudienceRoster.getType());
                doc.put("value", customAudienceRoster.getValue());
                return doc;
            });
            collection.insert(transform,WriteConcern.JOURNALED);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_HISTORY + "集合插入数据完成");
    }

    @Override
    public void saveCustomAudienceNameRosterHistory(Long custAudienceTemplateId, String version, OperateType operateType, String creator, String name) {
        if (StringUtils.isEmpty(name)) {
            logger.info(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_HISTORY + "入库对象为空，退出入库操作");
            return;
        }
        try {
            DBCollection collection = mongoDBClientPrimary.getCollection(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_HISTORY);
            BasicDBObject doc = new BasicDBObject();
            doc.put("customAudienceTemplateId", custAudienceTemplateId);
            doc.put("version", version);
            doc.put("creator", creator);
            doc.put("operateType", operateType.getValue());
            doc.put("createtime", new Date().getTime());
            doc.put("name", name);
            collection.insert(doc,WriteConcern.JOURNALED);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_HISTORY + "集合插入数据完成");
    }

    @Override
    public List<CustomAudienceTemplateRoster> getCustomAudienceRosterHistory(Long customAudienceTemplateId, String version) {
        List<CustomAudienceTemplateRoster> customAudienceRosterTemplateList = new ArrayList<CustomAudienceTemplateRoster>();
        try {
            DBCollection collection = mongoDBClientPrimary.getCollection(MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_HISTORY);
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("customAudienceTemplateId", customAudienceTemplateId);
            searchQuery.put("version", version);
            DBCursor cursor = collection.find(searchQuery);
            //循环输出结果
            collectCustomRoster(customAudienceTemplateId, customAudienceRosterTemplateList, cursor);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_CUSTOM_AUDIENCE_TEMPLATE_HISTORY + "集合插入数据完成");
        return customAudienceRosterTemplateList;
    }

    private void collectCustomRoster(Long customAudienceTemplateId, List<CustomAudienceTemplateRoster> customAudienceRosterList, DBCursor cursor) {
        while (cursor.hasNext()) {
            DBObject dbObject = cursor.next();
            CustomAudienceTemplateRoster customAudienceTemplateRoster = new CustomAudienceTemplateRoster();
            String type = (String) dbObject.get("type");
            String value = (String) dbObject.get("value");
            customAudienceTemplateRoster.setCustomAudienceId(customAudienceTemplateId);
            customAudienceTemplateRoster.setType(type);
            customAudienceTemplateRoster.setValue(value);
            customAudienceRosterList.add(customAudienceTemplateRoster);
        }
    }
}
